package vuelos;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class PlaySound extends Thread {
	
	private AudioFormat audioFormat;
	private AudioInputStream audioInputStream;
	private SourceDataLine sourceDataLine;
	
	public PlaySound(String snd){
		
		try {
			  audioInputStream = AudioSystem.getAudioInputStream(getClass().getResource(snd));
			  audioFormat =  audioInputStream.getFormat();
			  DataLine.Info dataLineInfo =
			     new DataLine.Info(
			            SourceDataLine.class,
			            audioFormat);
		      sourceDataLine = (SourceDataLine)AudioSystem.getLine(dataLineInfo);
		}
		catch (Exception ex) {
				System.out.println(ex.getMessage());
		}
		
	}
	
	public void run () {
	   byte tempBuffer[] = new byte[10000];

	   try{
		 sourceDataLine.open(audioFormat);
		 sourceDataLine.start();
			      
	     int cnt;
	     while((cnt = audioInputStream.read(tempBuffer,0,tempBuffer.length)) != -1){
		   if(cnt > 0){
			  sourceDataLine.write(tempBuffer, 0, cnt);
		   }
	     }	      
	     sourceDataLine.drain();
		 sourceDataLine.close();

	   }
	   catch (Exception e) {
			  e.printStackTrace();
			  System.exit(0);
	   }
		
	}

}
